import React, { useState, useEffect, ReactElement } from 'react';
import { Table, Button, Tag, Drawer, Form, Input, Radio, Select } from 'antd';
import {
  getUser,
  getDept,
  getRole,
  incrementUser,
  updateUser,
  deleteUser,
} from '../../../apis';
import { createFromIconfontCN } from '@ant-design/icons';
import qs from 'query-string';
import styles from './user.less';
import { SettingOutlined, DeleteOutlined } from '@ant-design/icons';

const { Option } = Select;
// IconFont就是图标组件
const IconFont = createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_2928153_a8ynxy9hpn5.js',
});

export default function User() {
  const [data, setData] = useState([]);
  const [dept, setDept] = useState([]);
  const [role, setRole] = useState([]);
  const [info, setInfo] = useState({});
  const [userId, setUserId] = useState({});
  const [status, setStatus] = useState();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    getUsers();
    getDeptData();
    getRoleData();
  }, []);

  const increment = () => {
    setVisible(true);
    setStatus('increment');
  };
  const update = (values) => {
    setVisible(true);
    setStatus('update');
    setInfo(values);
    setUserId(values.userId);
    console.log(values);
  };

  const onClose = () => {
    setVisible(false);
  };
  async function getUsers() {
    const result = await getUser({ pageSize: 100 });
    result.rows.map((item) => (item.key = item.userId));
    setData(result.rows);
    console.log(result.rows);
  }
  async function getDeptData() {
    const result = await getDept();
    setDept(result.rows.children);
    // console.log(result.rows.children);
  }
  async function getRoleData() {
    const result = await getRole();
    setRole(result.rows);
    console.log(result.rows);
  }

  const changePhone = (rule, value, callback) => {
    const reg = /^[1][3-9][0-9]{9}$/;
    if (reg.test(value)) {
      return Promise.resolve();
    } else {
      return Promise.reject('请输入正确的手机号');
    }
  };
  const onFinish = async (values) => {
    if (status == 'increment') {
      console.log(qs.stringify(values));
      const result = await incrementUser(qs.stringify(values));
      console.log('result' + result);
      getUsers();
      setVisible(false);
      console.log(result);
    } else if (status == 'update') {
      console.log(qs.stringify(userId));
      const result = await updateUser(qs.stringify({ ...values, userId }));
      console.log(result);
      getUsers();
      setVisible(false);
    }
  };

  const delUser = async (values) => {
    const result = await deleteUser(values.userId);
    getUsers();
  };

  function onSelectChange(selectedRowKeys) {
    console.log(selectedRowKeys);
    setSelectedRowKeys(selectedRowKeys);
  }

  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      width: 120,
    },
    {
      title: '性别',
      dataIndex: 'ssex',
      key: 'ssex',
      width: 60,
      render: (tags) => {
        switch (tags) {
          case '0':
            return '男';
          case '1':
            return '女';
          case '2':
            return '保密';
        }
      },
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      width: 120,
    },
    {
      title: '部门',
      dataIndex: 'deptName',
      key: 'deptName',
      width: 120,
    },
    {
      title: '电话',
      dataIndex: 'mobile',
      key: 'mobile',
      width: 120,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status) =>
        status ? (
          <Tag color="red" key={status}>
            有效
          </Tag>
        ) : (
          <Tag color="red" key={status}>
            锁定
          </Tag>
        ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 220,
    },
    {
      title: '操作',
      key: 'mobile',
      width: 120,
      render: (tags) => {
        return (
          <>
            <SettingOutlined onClick={() => update(tags)} />
            &nbsp;
            <DeleteOutlined onClick={() => delUser(tags)} />
          </>
          // <IconFont onClick={update} type={`icon-dashboard`}></IconFont>
        );
      },
    },
  ];
  return (
    <div>
      <Button type="primary" ghost onClick={increment}>
        新增
      </Button>
      <Table
        rowSelection={{
          selectedRowKeys,
          onChange: onSelectChange,
        }}
        rowKey="name"
        columns={columns}
        dataSource={data}
      />
      {/* <IconFont type={`icon-dashboard`}></IconFont> */}
      <Drawer
        title={status == 'increment' ? '新增用户' : '修改用户'}
        placement="right"
        closable={false}
        visible={visible}
      >
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          autoComplete="off"
          initialValues={info}
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[{ required: true, message: '请输入用户名!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item label="密码" name="password">
            <Input.Password />
          </Form.Item>

          <Form.Item
            label="邮箱"
            name="email"
            rules={[
              {
                type: 'email',
                message: '请输入正确的邮箱',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="手机号"
            name="mobile"
            rules={[
              {
                validator: changePhone,
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="roleId"
            label="角色"
            rules={[
              {
                required: true,
                message: '请选择你的角色!',
                type: 'array',
              },
            ]}
          >
            <Select mode="multiple" placeholder="请选择你的角色">
              {role.map((item) => {
                return (
                  <Option key={item.roleId} value={item.roleId}>
                    {item.roleName}
                  </Option>
                );
              })}
            </Select>
          </Form.Item>

          <Form.Item name="deptId" label="部门">
            <Select allowClear={true}>
              {dept.map((item) => {
                return (
                  <Option key={item.key} value={item.id}>
                    {item.title}
                  </Option>
                );
              })}
            </Select>
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            rules={[
              {
                required: true,
                message: '请选择你的状态!',
              },
            ]}
          >
            <Radio.Group>
              <Radio value="0">锁定</Radio>
              <Radio value="1">有效</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            name="ssex"
            label="性别"
            rules={[
              {
                required: true,
                message: '请选择你的性别!',
              },
            ]}
          >
            <Radio.Group>
              <Radio value="0">男</Radio>
              <Radio value="1">女</Radio>
              <Radio value="2">保密</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button onClick={onClose}>取消</Button>
            &nbsp;
            <Button type="primary" htmlType="submit">
              确定
            </Button>
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  );
}
